package org.jeecg.modules.clue.expose;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.clue.bo.ClueRecordExposeBo;
import org.jeecg.modules.clue.bo.ClueRecordPushExpose;
import org.jeecg.modules.clue.entity.ClueRecord;
import org.jeecg.modules.clue.entity.ClueUserTpCarRelate;
import org.jeecg.modules.clue.enums.ClueWriteMode;
import org.jeecg.modules.clue.req.ClueHistoryResend;
import org.jeecg.modules.clue.service.IClueRecordService;
import org.jeecg.modules.clue.service.IClueUserTpCarRelateService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.simpleframework.xml.core.Validate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Api(tags = "线索接口暴露API")
@RestController
@RequestMapping("/clue/recordExposeApi")
@Slf4j
public class ClueRecordExposeApi {
    @Resource
    ISysUserService sysUserService;
    @Resource
    IClueUserTpCarRelateService clueUserTpCarRelateService;
    @Resource
    IClueRecordService clueRecordService;


    /**
     * 线索推送接口
     *
     * @param clueRecordPushExpose
     * @return
     */
    @AutoLog(value = "线索接口暴露API-线索推送接口")
    @ApiOperation(value = "线索接口暴露API-线索推送接口", notes = "线索接口暴露API-线索推送接口")
    @PostMapping(value = "/push")
    public Result<JSONObject> push(@RequestBody @Validate ClueRecordPushExpose clueRecordPushExpose) throws Exception {
        String key = clueRecordPushExpose.getKey();
        SysUser channelUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getAppKey, key));
        if (null == channelUser) {
            throw new RuntimeException("当前key不存在,请联系平台管理员");
        }
        String signature = generateMD5Signature(String.format("%s%s%s", key, clueRecordPushExpose.getTime(), clueRecordPushExpose.getClue()));

        if (!signature.equals(clueRecordPushExpose.getSign())) {
            throw new RuntimeException("签名不正确");
        }
        ClueRecordExposeBo clueRecordExposeBo = JSON.parseObject(clueRecordPushExpose.getClue(), ClueRecordExposeBo.class);
        if (StringUtils.isBlank(clueRecordExposeBo.getPhone())) {
            throw new RuntimeException("手机号不能为空");
        }
        if (!PhoneUtil.isMobile(clueRecordExposeBo.getPhone())) {
            throw new RuntimeException("手机号格式错误");
        }

        if (StringUtils.isBlank(clueRecordExposeBo.getCity())) {
            throw new RuntimeException("城市不能为空");
        }


        // 检测用户可用性
        SysUser sysUser = sysUserService.getUserByName(channelUser.getUsername());
        if (sysUser == null) {
            throw new RuntimeException("线索来源用户名不存在,请联系系统管理员");
        }
        Result result = sysUserService.checkUserIsEffective(sysUser);
        if (CommonConstant.SC_INTERNAL_SERVER_ERROR_500.equals(result.getCode())) {
            throw new RuntimeException(result.getMessage());
        }
        // 查询当前线索来源，启用的三方平台
        List<ClueUserTpCarRelate> tpCarRelateList = clueUserTpCarRelateService.list(new LambdaQueryWrapper<ClueUserTpCarRelate>().eq(ClueUserTpCarRelate::getUserId, sysUser.getId()));
        List<ClueUserTpCarRelate> pushCarPlateList = tpCarRelateList.parallelStream().filter(new Predicate<ClueUserTpCarRelate>() {
            @Override
            public boolean test(ClueUserTpCarRelate clueUserTpCarRelate) {
                String cityListStr = Optional.ofNullable(clueUserTpCarRelate.getCityList()).orElse("");
                return  StringUtils.isBlank(clueUserTpCarRelate.getCityList()) || Arrays.asList(cityListStr.split(",")).contains(clueRecordExposeBo.getCity());
            }
        }).collect(Collectors.toList());

        if (pushCarPlateList.isEmpty()) {
            throw new RuntimeException("平台暂未覆盖此城市");
        }


        ClueRecord clueRecord = new ClueRecord();
        BeanUtil.copyProperties(clueRecordExposeBo, clueRecord);
        clueRecord.setRecordNo(Objects.requireNonNull(FillRuleUtil.executeRule("clue_record_no_rule", (JSONObject) JSON.toJSON(clueRecord))).toString());
        clueRecord.setWriteMode(ClueWriteMode.外部对接.status);
        clueRecord.setSource(channelUser.getUsername());
        clueRecordService.save(clueRecord);
        // 分发任务
        clueRecordService.distributeTask(clueRecord);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ccid",clueRecord.getRecordNo());
        return Result.OK(jsonObject);
    }


    /**
     * 生成MD5签名
     *
     * @param param
     * @return
     * @throws Exception
     */
    public static String generateMD5Signature(String param) throws Exception {
        // 创建MD5摘要算法对象
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 将拼接口的字符串转为字节数组
        byte[] bytes = param.getBytes(StandardCharsets.UTF_8);

        // 计算MD5摘要
        byte[] digest = md.digest(bytes);

        // 将摘要转换为16进制字符串
        StringBuilder hexString = new StringBuilder();

        for (byte b : digest) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }


    public static void main(String[] args) throws Exception {
        String key = "8a742df694639d0a0194639decd40002";
        long time = System.currentTimeMillis();
        JSONObject clue = new JSONObject();
        clue.put("city","苏州");
        clue.put("phone","18600000001");
        clue.put("brandName","红旗");
        clue.put("seriesName","红旗h6");
        clue.put("specName","智商版");
        clue.put("firstRegTime","2023-01-01");
        clue.put("mileage",1);
        String sign = generateMD5Signature(String.format("%s%s%s", key, time, clue.toJSONString()));

        JSONObject body = new JSONObject();
        body.put("key",key);
        body.put("time",time);
        body.put("sign",sign);
        body.put("clue",JSONObject.toJSONString(clue));

        HttpRequest request = HttpUtil.createPost("http://clue-server.haisuoshuju.cn/haisuoshuju/clue/recordExposeApi/push");
        request.contentType("application/json");
        request.body(body.toJSONString());
        HttpResponse response = request.execute();
        System.out.println(response.body());
    }
}
